//
//  AlarmEditView.m
//  StormWatch
//
//  Created by 王岩 on 2024/9/18.
//

#import "AlarmEditView.h"
#import "JYPopContainerView.h"
#import "JYRoot.h"
#import "YYCategoriesMacro.h"
#import "WeeksViewCell.h"

@interface AlarmEditView ()<UIPickerViewDelegate, UIPickerViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, weak) JYPopContainerView *popView;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UISwitch *switchBtn;
@property (nonatomic, strong) AlermModel *model;
@property (nonatomic, strong) UIButton *sureBtn;
@property (nonatomic, strong) NSArray *hoursArr, * minArr, *weekArr;
@property (nonatomic, assign) NSInteger hourIndex;
@property (nonatomic, assign) NSInteger minuteIndex;
@property (nonatomic, assign) NSInteger alermOpen;
@property (nonatomic, strong) NSMutableString *repeatString;

@end

@implementation AlarmEditView

- (instancetype)initWithAlertModel:(AlermModel *)model {
   if (self = [super init]) {
       _model = model;
       _alermOpen = model.isOpen;
       _repeatString = [[NSMutableString alloc] initWithString:model.repeat];
       self.weekArr = @[SWString(@"Mon"),SWString(@"Tue"),SWString(@"Wed"),SWString(@"Thu"),SWString(@"Fri"),SWString(@"Sat"),SWString(@"Sun")];
     
       [self setupUI];
       [self bar];
       self.bar.titleLab.text = SWString(@"Edit alarm");
       
       self.sureBtn = [SWInitializer jy_initButtonWithTarget:self action:@selector(sureBtnAction) title:SWString(@"save") titleColor:[UIColor blackColor] font:[UIFont systemFontOfSize:16] bgColor:[UIColor clearColor] on:self layout:^(MASConstraintMaker * _Nonnull make) {
           kMakeRV(-10);
           kMakeTV(- self.jy_bar_h);
           kMakeHV(self.jy_bar_h);
       }];
       
   }
   return self;
}

- (void) sureBtnAction {
    self.model.repeat = self.repeatString;
    self.model.isOpen = self.alermOpen;
    self.model.alert_H = [self.hoursArr[self.hourIndex] intValue];
    self.model.alert_M = [self.minArr[self.minuteIndex] intValue];
    self.sureBlock(self.model);
}

- (void)setupUI {
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 300)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self addSubview:self.pickerView];
    
    UILabel * repet = [SWInitializer jy_initLabelWithText:SWString(@"Repeat") textColor:[UIColor blackColor] font:S_font(17) bgColor:[UIColor clearColor] on:self layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(10);
        kMakeTV(300);
        kMakeHV(20);
    }];
    
    self.switchBtn = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    [self.switchBtn addTarget:self action:@selector(onClickRepeat:) forControlEvents:UIControlEventValueChanged];
    [self addSubview:self.switchBtn];
    [self.switchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        kMakeRV(-10);
        kMakeCenterY(repet.mas_centerY);
    }];
    self.switchBtn.on = [self.model.repeat hasSuffix:@"1"];
    
    [self addSubview:self.collectionView];
    
    if (self.switchBtn.isOn) {
        self.collectionView.hidden = NO;
       
        [self.collectionView reloadData];
    }else {
        self.collectionView.hidden = YES;
    }
}

- (void)onClickRepeat:(UISwitch *)sender {
    if (sender.isOn) {
        self.collectionView.hidden = NO;
        [self.repeatString replaceCharactersInRange:NSMakeRange(7, 1) withString:@"1"];
    }else {
        self.collectionView.hidden = YES;
        [self.repeatString replaceCharactersInRange:NSMakeRange(7, 1) withString:@"0"];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.hoursArr.count;
    }
    return self.minArr.count;
}
#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if(component == 0) {
        self.hourIndex = row;
    }else  {
        self.minuteIndex = row;
    }
    NSLog(@"%ld:%ld",self.hourIndex,self.minuteIndex);
}
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if(component == 0){
        return [self.hoursArr objectAtIndex:row];
    }else {
        return [self.minArr objectAtIndex:row];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 7;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WeeksViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WeeksViewCell" forIndexPath:indexPath];
    cell.valueLab.text = self.weekArr[indexPath.row];
    
    if ([[self.repeatString substringWithRange:NSMakeRange(6 - indexPath.row, 1)] isEqualToString:@"1"]) {
        cell.valueLab.backgroundColor = [UIColor orangeColor];
        cell.valueLab.textColor = [UIColor whiteColor];
    }else {
        cell.valueLab.textColor = [UIColor blackColor];
        cell.valueLab.backgroundColor = [UIColor whiteColor];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString * s = [self.repeatString substringWithRange:NSMakeRange(6 - indexPath.row, 1)];
    if ([s isEqualToString:@"1"]) {
        [self.repeatString replaceCharactersInRange:NSMakeRange(6 - indexPath.row, 1) withString:@"0"];
    }else {
        [self.repeatString replaceCharactersInRange:NSMakeRange(6 - indexPath.row, 1) withString:@"1"];
    }
    
    [collectionView reloadData];
}

- (void)dimiss
{
    [self.popView dissmiss];
}
- (void)show
{
    if (self.popView) {
        [self.popView removeFromSuperview];
    }
    JYPopContainerView *popView = [JYRoot popBottomView:self animation:YES maker:^(MASConstraintMaker * _Nonnull make) {
        kMakeLRV(0);
        kMakeBV(0);
        kMakeHV(klSafeAreaEdgeInsets.bottom  + 410);
    } block:nil];
    [popView layoutSubviews];
    _popView = popView;

    @weakify(popView);
    self.eventTransmissionBlock = ^(id  _Nonnull params, NSInteger tag) {
        @strongify(popView);
        if (tag == 0) {
            [popView dissmiss];
        }
    };

    [self.superview layoutIfNeeded];

}


- (NSString *)containerColor {
    return @"#FFFFFF";
}

- (NSArray *)hoursArr {
    if (!_hoursArr) {
        _hoursArr = @[@"00",@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23"];
    }
    return _hoursArr;
}

- (NSArray *)minArr {
    if (!_minArr) {
        NSMutableArray * arr = [[NSMutableArray alloc] init];
        for (int i = 0; i < 60; i ++) {
            [arr addObject:[NSString stringWithFormat:@"%02d", i]];
        }
        _minArr = arr;
    }
    return _minArr;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((kScreenWidth - 80)/ 7, 45);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.scrollDirection = 1;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 340, kScreenWidth, 45) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[WeeksViewCell class] forCellWithReuseIdentifier:@"WeeksViewCell"];
    }
    return _collectionView;
}


// 在view中重写以下方法，其中self.button就是那个希望被触发点击事件的按钮
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        // 转换坐标系
        CGPoint newPoint = [self.sureBtn convertPoint:point fromView:self];
        // 判断触摸点是否在button上
        if (CGRectContainsPoint(self.sureBtn.bounds, newPoint)) {
            view = self.sureBtn;
        }
    }
    return view;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
